package com.qeegoo.b2bautozityp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.qeegoo.b2bautozityp.api.HttpConsts;
import com.qeegoo.b2bautozityp.app.App;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import base.lib.util.ToastUtils;

/**
 * Created by 王少岩 on 2016/9/26.
 */

public class SelectHostActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private static final List<Host> hosts;
    public static final Pattern Http_or_Https_URL_Pattern = Pattern.compile("(http|https|Http|Https|HTTP|HTTPS):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?");

    static {
        hosts = new ArrayList<Host>();
        hosts.add(new Host("正式", "http://api.jyj.b2bex.com/"));
        hosts.add(new Host("测试", "http://api.jyj.b2bex.com/"));
    }

    ListView listAppHost;
    EditText editAPPHost;
    ImageView back;
    TextView save;

    private HostAdapter appHostAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_host_page);
        listAppHost = (ListView) findViewById(R.id.listview_app);
        editAPPHost = (EditText) findViewById(R.id.eidt_app_host);
        back = (ImageView) findViewById(R.id.back);
        save = (TextView) findViewById(R.id.save);
        appHostAdapter = new HostAdapter();

        String appHost = HttpConsts.getServer();
        appHostAdapter.setSelectedHost(appHost);
        editAPPHost.setText(appHost);
        editAPPHost.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                appHostAdapter.setSelectedHost(editAPPHost.getText().toString());
            }
        });

        listAppHost.setAdapter(appHostAdapter);
        listAppHost.setOnItemClickListener(this);
        back.setOnClickListener(v -> finish());
        save.setOnClickListener(v -> {
            boolean result = saveHost();
            if (result) {
                App.getInstance().initInjector();
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String url = hosts.get(position).getUrl();
        if (parent.getId() == R.id.listview_app) {
            editAPPHost.setText(url);
            appHostAdapter.setSelectedHost(url);
        }
    }

    private boolean saveHost() {
        String appHost = editAPPHost.getText().toString();
        if (TextUtils.isEmpty(appHost)) {
            ToastUtils.showToast("请选择B2B host");
            return false;
        }
        if (!isHttpAddr(appHost)) {
            ToastUtils.showToast("B2B host 不是有效的http地址");
            return false;
        }
        if (!appHost.endsWith("/")) {
            appHost += "/";
        }

        HttpConsts.setServer(appHost);
        return true;
    }

    class HostAdapter extends BaseAdapter {

        String selectedHost;

        public String getSelectedHost() {
            return selectedHost;
        }

        public void setSelectedHost(String selectedHost) {
            this.selectedHost = selectedHost;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return hosts.size();
        }

        @Override
        public Object getItem(int position) {
            return hosts.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflateConvertView();
            }
            Host host = (Host) getItem(position);
            Holder holder = (Holder) convertView.getTag();

            holder.name.setText(host.name);
            holder.url.setText(host.url);

            boolean isSelected = host.url.equals(getSelectedHost());
            holder.name.setSelected(isSelected);

            return convertView;
        }

        private View inflateConvertView() {
            View view = View.inflate(getBaseContext(), R.layout.select_host_item, null);
            Holder holder = new Holder();
            holder.name = (TextView) view.findViewById(R.id.textview_name);
            holder.url = (TextView) view.findViewById(R.id.textview_url);
            view.setTag(holder);
            return view;
        }

    }

    static class Holder {
        TextView name;
        TextView url;
    }

    public static class Host {
        private String name;
        private String url;

        public Host(String name, String url) {
            this.name = name;
            this.url = url;
        }

        public String getName() {
            return name;
        }

        public String getUrl() {
            return url;
        }

    }

    /**
     * 正则表达式匹配http或https地址
     *
     * @param httpAddr
     * @return
     */
    public static boolean isHttpAddr(String httpAddr) {
        return Http_or_Https_URL_Pattern.matcher(httpAddr).matches();
    }
}
